package system;
import java.sql.*;

public class 
OracleConnection 
{	private static OracleConnection singleton_instance = null;
	protected Connection con = null;
	protected boolean driverLoaded = false;
	
	protected 
	OracleConnection(){}
	 
	// When one thread is executing a synchronized method on an object, all
	// other threads that invoke synchronized methods on the same object must
	// block until the first thread is done with the object.
	//
	// Constructors cannot be synchronized, since only the thread creating the
	// object has access to that object.
	//
	// All reads and writes to an object that can be accessed by multiple
	// threads should be done through synchronized methods, unless more subtle
	// synchronization mechanisms are being used.
	public synchronized static OracleConnection 
	getInstance() {
		if (singleton_instance == null)
		{ singleton_instance = new OracleConnection(); }
		return singleton_instance;
    }
	
	 public synchronized boolean 
	 connect(String username, String password)
	 {	try {
		    String url = "jdbc:oracle:thin:@localhost:1521:ug";
	
		    if (!driverLoaded) {
		    	DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
		    	System.out.println("\nConnected to Oracle!\n");
		    	driverLoaded = true; 
		    }
		    con = DriverManager.getConnection(url, username, password);
		    con.setAutoCommit(false);
		    return true; 
		}
		catch (SQLException ex) { return false; }
    }
	 
	public synchronized Connection 
	getConnection(){ return con; }
	 
    public synchronized boolean 
    isDriverLoaded() { return driverLoaded; }

    protected void 
    finalize() 
    throws Throwable 
    {	if (con != null){ con.close(); }
    	super.finalize();	
    }
}
